package top.lshaci.framework.file.oss.properties;

import com.aliyun.oss.crypto.SimpleRSAEncryptionMaterials;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

/**
 * FrameworkOssProperties
 *
 * @author lshaci
 * @since 1.0.9
 */
@Data
@Validated
@ConfigurationProperties(FrameworkOssProperties.PREFIX)
public class FrameworkOssProperties {

    /**
     * 配置前缀
     */
    public static final String PREFIX = "framework.oss";

    /**
     * 开始 oss 配置
     */
    private boolean enabled = true;

    /**
     * 存储文件的 bucket
     */
    @NotBlank
    private String bucket;

    /**
     * oss encryption 配置
     */
    @Valid
    private Encryption encryption = new Encryption();

    /**
     * oss 加密客户端配置
     */
    @Data
    public class Encryption {

        /**
         * 是否开启 oss encryption 配置
         */
        private boolean enabled = false;

        /**
         * 用于文件加密的公钥
         */
        @NotBlank
        private String rsaPublicKey;

        /**
         * 用于文件加密的私钥
         */
        @NotBlank
        private String rsaPrivateKey;

        /**
         * 根据公钥和私钥生成密钥对
         *
         * @return 密钥对
         */
        public KeyPair keyPair() {
            RSAPrivateKey privateKey = SimpleRSAEncryptionMaterials.getPrivateKeyFromPemPKCS1(rsaPrivateKey);
            RSAPublicKey publicKey = SimpleRSAEncryptionMaterials.getPublicKeyFromPemX509(rsaPublicKey);
            return new KeyPair(publicKey, privateKey);
        }
    }
}
